﻿Imports System.Linq
Imports MNL.Store

Partial Class Controls_ShoppingCart
    Inherits System.Web.UI.UserControl

    Public Sub UpdateTotals()
        'update part quantities
        For Each row As GridViewRow In gvwOrderItems.Rows

            Dim id = Convert.ToInt32(gvwOrderItems.DataKeys(row.RowIndex)(0))
            Dim quantity = Convert.ToInt32(CType(row.FindControl("txtQuantity"), TextBox).Text)
            'CType(HttpContext.Current.Profile, ProfileCommon).ShoppingCart.UpdatePartQuantity(id, quantity)
            Profile.ShoppingCart.UpdatePartQuantity(id, quantity)
        Next

        'show subtotal and total amounts
        lblSubtotal.Text = FormatPrice(Profile.ShoppingCart.Total)
        lblTotal.Text = FormatPrice(Profile.ShoppingCart.Total + GetShippingMethodCost())

    End Sub

    Private Sub BindOrderedItemsGrd()

        Dim OrderedParts = CurrentUserShoppingCart.GetItems()
        If OrderedParts IsNot Nothing AndAlso OrderedParts.Count > 0 Then

            gvwOrderItems.DataSource = OrderedParts
            gvwOrderItems.DataBind()

            UpdateTotals()
        Else
            panTotals.Visible = False
        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindOrderedItemsGrd()
    End Sub


    Protected Function FormatPrice(ByVal price As Object) As String
        Return Convert.ToDecimal(price).ToString("N2") + " " + "£"
    End Function

    Protected Sub btnUpdateTotals_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateTotals.Click
        UpdateTotals()
    End Sub


    Protected Sub gvwOrderItems_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvwOrderItems.RowCommand

    End Sub

    Protected Sub gvwOrderItems_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvwOrderItems.RowDeleting

        Dim ID As Integer = CInt(gvwOrderItems.DataKeys(e.RowIndex).Value)

        CurrentUserShoppingCart.DeletePartItem(ID)

        BindOrderedItemsGrd()

        updPanelShoppingCart.Update()
    End Sub

    Private Function GetShippingMethodCost() As Decimal

        Dim svalue As String = ddlShippingMethods.SelectedValue

        Dim dValue = svalue.Remove(svalue.Length - 1, 1).Trim

        Return dValue
    End Function

    Public Property UpdateMode() As UpdatePanelUpdateMode
        Get
            Return Me.updPanelShoppingCart.UpdateMode
        End Get
        Set(ByVal value As UpdatePanelUpdateMode)
            Me.updPanelShoppingCart.UpdateMode = value
        End Set
    End Property

    Public Sub Update()
        Me.updPanelShoppingCart.Update()
    End Sub

End Class
